﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;


using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsBusinessCategoryTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
   public class BusinessCategory:BOBase
    {
        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected BusinessCategory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the BusinessCategory.
        /// </summary>
        public int BusinessCatgryID
        {
            get { return _businesscatgryID; }
            set
            {
                if (_businesscatgryID != value)
                {
                    if (OnPropertyChanging("BusinessCatgryID", _businesscatgryID, value))
                    {
                        int oldValue = _businesscatgryID;
                        _businesscatgryID = value;

                        OnPropertyChanged("BusinessCatgryID", oldValue, value);
                    }
                }
            }
        }  private int _businesscatgryID = -1;

        /// <summary>
        /// Business Category Value.
        /// </summary>
        public string BusinessCatgryName
        {
            get { return _businesscatgryname; }
            set
            {
                if (_businesscatgryname != value)
                {
                    if (OnPropertyChanging("BusinessCatgryName", _businesscatgryname, value))
                    {
                        string oldValue = _businesscatgryname;
                        _businesscatgryname = value;
                        OnPropertyChanged("BusinessCatgryName", oldValue, value);
                    }
                }
            }
        }  private string _businesscatgryname = null;


        /// <summary>
        /// Business Category Description.
        /// </summary>
        public string BusinessCatgryDescription
        {
            get { return _businesscatgrydescription; }
            set
            {
                if (_businesscatgrydescription != value)
                {
                    if (OnPropertyChanging("BusinessCatgryDescription", _businesscatgrydescription, value))
                    {
                        string oldValue = _businesscatgrydescription;
                        _businesscatgrydescription = value;
                        OnPropertyChanged("BusinessCatgryDescription", oldValue, value);
                    }
                }
            }
        }  private string _businesscatgrydescription = null;

        /// <summary>
        /// Business Category Add By.
        /// </summary>
        public string AddBy
        {
            get { return _addby; }
            set
            {
                if (_addby != value)
                {
                    if (OnPropertyChanging("AddBy", _addby, value))
                    {
                        string oldValue = _addby;
                        _addby = value;
                        OnPropertyChanged("AddBy", oldValue, value);
                    }
                }
            }
        }  private string _addby = null;



        /// <summary>
        /// Date/time at which the BusinessCategory was created.
        /// </summary>
        public DateTime? DateAdded
        {
            get { return _dateAdded; }
            set
            {
                if (_dateAdded != value)
                {
                    if (OnPropertyChanging("DateAdded", _dateAdded, value))
                    {
                        DateTime? oldValue = _dateAdded;
                        _dateAdded = value;
                        OnPropertyChanged("DateAdded", oldValue, value);
                    }
                }
            }
        }  private DateTime? _dateAdded = null;

        /// <summary>
        /// Date/time at which the BusinessCategory was updated.
        /// </summary>
        public DateTime? DateModified
        {
            get { return _dateModified; }
            set
            {
                if (_dateModified != value)
                {
                    if (OnPropertyChanging("DateModified", _dateModified, value))
                    {
                        DateTime? oldValue = _dateModified;
                        _dateModified = value;
                        OnPropertyChanged("DateModified", oldValue, value);
                    }
                }
            }
        }  private DateTime? _dateModified = null;


        /// <summary>
        /// True iff the Admin has made this BusinessCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty BusinessCategory object.
        /// </summary>
        public static BusinessCategory CreateNew()
        {
            BusinessCategory obj = new BusinessCategory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.DateAdded = DateTime.Now;
            obj.DateModified = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static BusinessCategory CreateNew(BusinessCategoryCollection collection)
        {
            BusinessCategory obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (BusinessCategory businesscategory in collection)
            {
                if (businesscategory.BusinessCatgryID < minVal)
                    minVal = businesscategory.BusinessCatgryID;
            }
            obj.BusinessCatgryID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllBusinessCategories

        /// <summary>
        /// Returns a collection of all BusinessCategory.
        /// </summary>
        public static BusinessCategoryCollection GetAllBusinessCategories()
        {
           BusinessCatagoryTableAdapter adapter = new BusinessCatagoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

           dsBusinessCategory.BusinessCatagoryDataTable tbl = adapter.GetData(null);

           BusinessCategoryCollection list = new BusinessCategoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsBusinessCategory.BusinessCatagoryRow row in tbl.Rows)
                {
                    BusinessCategory businessCategory = new BusinessCategory();
                    RelationalToObject(businessCategory, row);
                    list.Add(businessCategory);
                }
            }

            return (list);
        }

        #endregion

        #region GetBusinessCategoryByID

        /// <summary>
        /// Returns an BusinessCategory object for the specified 'BusinessCatgryID' or null if no BusinessCategory with the specified parameter(s) exists.
        /// </summary>
        public static BusinessCategory GetBusinessCategoryByID(int businesscatgryid)
        {
           BusinessCatagoryTableAdapter adapter = new BusinessCatagoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
           dsBusinessCategory.BusinessCatagoryDataTable tbl = adapter.GetData(businesscatgryid);

            if (tbl.Rows.Count == 1)
            {
                BusinessCategory bc = new BusinessCategory();
                RelationalToObject(bc, tbl.Rows[0]);
                return (bc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'ID' returned more than one User record.");

            return (null);
        }

        #endregion

        #region GetBusinessCategoryByBusinessCatgryName

        /// <summary>
        /// Returns an BusinessCategory object for the specified 'BusinessCatgryName' or null if no BusinessCategory with the specified parameter(s) exists.
        /// </summary>
        public static BusinessCategory GetBusinessCategoryByBusinessCatgryName(string businesscatgryname)
        {
            BusinessCatagoryTableAdapter adapter = new BusinessCatagoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsBusinessCategory.BusinessCatagoryDataTable tbl = adapter.GetDataByBusinessCatgryName(businesscatgryname);

            if (tbl.Rows.Count == 1)
            {
                BusinessCategory bc = new BusinessCategory();
                RelationalToObject(bc, tbl.Rows[0]);
                return (bc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'Name' returned more than one businesscategory.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified BusinessCategory.
        /// </summary>
        public static void Update(BusinessCategory obj)
        {
            bool updateBusinessCategory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateBusinessCategory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateBusinessCategory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

           dsBusinessCategory.BusinessCatagoryDataTable tbl = null;
            if (updateBusinessCategory)
            {
               
               BusinessCatagoryTableAdapter adapter = new BusinessCatagoryTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsBusinessCategory.BusinessCatagoryDataTable();
               dsBusinessCategory.BusinessCatagoryRow row = tbl.NewBusinessCatagoryRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }
       
        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (BusinessCatgryID<= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("BusinessCatgryID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // BusinessName is required.
                if ((BusinessCatgryName == null) || (BusinessCatgryName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("BusinessCatgryName", "BusinessCategory is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("BusinessCategory: BCID={0}, BusinessCatgryName={1}, {2}", BusinessCatgryID, BusinessCatgryName, BusinessCatgryDescription, AddBy));
        }

        #endregion

        #endregion
    }

    /// <summary>
    /// Collection of 0 or more SubAdmin objects.
    /// </summary>

    public class BusinessCategoryCollection : List<BusinessCategory> 
    {
        
        #region Types

        public class UserComparer : IComparer<BusinessCategory>
        {
            public int Compare(BusinessCategory user1, BusinessCategory user2)
            {
                return (String.Compare(user1.BusinessCatgryName, user2.BusinessCatgryName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByBusinessCategoryID

        public BusinessCategory FindByBusinessCategoryID(int businesscategoryID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].BusinessCatgryID == businesscategoryID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindByBusinessCategoryName

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public BusinessCategory FindByBusinessCategoryName(string businesscategoryname)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].BusinessCatgryName == businesscategoryname)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
